<template>
 <div class="profile-page">

  <div class="user-info">
    <div class="container">
      <div class="row">

        <div class="col-xs-12 col-md-10 offset-md-1">
          <img src="http://i.imgur.com/Qr71crq.jpg" class="user-img" />
          <h4>{{ profile.username }}</h4>
          <p>
            {{ profile.bio }}
          </p>

          <template v-if="user.username === profile.username">
            <nuxt-link to="/settings">
            <button class="btn btn-sm btn-outline-secondary action-btn">
             <i class="ion-gear-a"></i>
             &nbsp;
              Edit Profile Settings
             </button>
             </nuxt-link>
          </template>
          <template v-else>
          <button 
            :class="{active: profile.following}"
            class="btn btn-sm btn-outline-secondary action-btn" :disabled="requestLoading.follow" @click="onFollow" >
            <i class="ion-plus-round"></i>
            &nbsp;
            {{ profile.following ? 'Unfollow' : 'Follow' }} {{ profile.username }} 
          </button>
          </template>

         
        </div>

      </div>
    </div>
  </div>

  <div class="container">
    <div class="row">

      <div class="col-xs-12 col-md-10 offset-md-1">
        <div class="articles-toggle">
          <ul class="nav nav-pills outline-active">
            <li class="nav-item">
              <nuxt-link class="nav-link"
                exact
                :class="{
                  active: tab !== 'favorite'
                }"
                :to="{
                name:'profile',
                params: {
                  username: profile.username
                }
              }">My Articles</nuxt-link>
            </li>
            <li class="nav-item" :active="tab === 'favorite'">
              <nuxt-link 
                exact
                :class="{
                  active: tab === 'favorite'
                }"
                class="nav-link" :to="{
                name:'profile',
                params: {
                  username: profile.username,
                },
                query: {
                  tab: 'favorite'
                }
              }">Favorited Articles</nuxt-link>
            </li>
          </ul>
        </div>

        <div class="article-preview" v-for="article in articles" :key="article.slug">
           <div class="article-meta">
            <nuxt-link :to="{name:'profile',
            params: {
              username: article.author.username
            }}"><img :src="article.author.image" /></nuxt-link>
            <div class="info">
              <nuxt-link :to="{name:'profile',
            params: {
              username: article.author.username
            }}" class="author">{{ article.author.username }}</nuxt-link>
              <span class="date">{{ article.createdAt | date("MMM DD,YYYY") }}</span>
            </div>
            <button 
              :disabled="article.favoriteDisabled"
              @click="onFavorite(article)"
              class="btn btn-outline-primary btn-sm pull-xs-right" 
              :class="{
              active: article.favorited
              }"
            >
              <i class="ion-heart"></i> {{ article.favoritesCount }}
            </button>
          </div>
          <nuxt-link class="preview-link"
          :to="{
            name:'article',
            params: {
              slug: article.slug
            }
          }"
          >
            <h1>{{ article.title }}</h1>
            <p>{{ article.description }}</p>
            <span>Read more...</span>
          </nuxt-link>
        </div>


         <!-- 分页列表    -->

        <nav>
          <ul class="pagination">
            <li class="page-item" 
            v-for="item in totalPage" 
            :key="item" 
            :class="{
              active: item === page
            }">
              <nuxt-link 
              class="page-link" 
              :to="{
                name: 'profile',
                params: {
                  username: profile.username
                },
                query: {
                  tab: tab !== 'favorite' ? undefined : tab,
                  page: item
                 
                }
              }">{{ item }}</nuxt-link>
            </li>
          </ul>
        </nav>


      </div>

    </div>
  </div>

</div>
</template>

<script>
import { getProfile } from '@/api/profile'
import { getArticles, addFavorite, deleteFavorite, followUser, unFollowUser } from '@/api/article'
import { mapState } from 'vuex'
export default {
    name:'profile',
    computed: {
      ...mapState(['user']),
       totalPage() {
        return Math.ceil(this.count / this.limit)
      }
    },
    async asyncData ({ query, params }) {

      const { tab } = query
      // console.log(tab)
      const page = Number.parseInt(query.page || 1)
      const limit = 20
      const [profileRes, articleRes] = await Promise.all([
        getProfile(params.username),
        getArticles({
          author: tab === 'favorite' ? undefined : params.username,
          favorited: tab === 'favorite' ? params.username : undefined,
          limit: limit,
          offset: (page - 1) * limit 
        })
      ])
      const { data } = profileRes
      const { data: articles } = articleRes
      articles.articles.forEach( article => {
        article.favoriteDisabled = false
      })
      return {
          profile: data.profile,
          articles: articles.articles,
          count: articles.articlesCount,
          tab: tab || '',
          limit: limit,
          page: page,
          requestLoading: {
            follow: false
          }
      }
    },
    watchQuery: ['tab', 'page'],
    methods: {
      async onFavorite (article) {
        article.favoriteDisabled = true
        if (article.favorited) {
          // 取消点赞
         
          await deleteFavorite(article.slug)
          article.favorited = false
          article.favoritesCount -= 1
        } else {
          // 添加点赞
          await addFavorite(article.slug)
         
          article.favorited = true
          article.favoritesCount += 1
        }
         article.favoriteDisabled = false
      },
      async onFollow () {
        this.requestLoading.follow = true
        if (this.profile.following) {
            // 取消关注
            await unFollowUser(this.profile.username)
            this.profile.following = false
        } else {
            // 关注
            await followUser(this.profile.username)
            this.profile.following = true
        }
        this.requestLoading.follow = false
      },
    }
};
</script>

